from flask import Flask, request
from time import time
from datetime import datetime
from json import dumps, loads
from os import path
from csv import writer
app = Flask(__name__)

file_dir = path.dirname(__file__)
with open(f'{file_dir}/html/verify.html', 'r', encoding='utf8') as verify_file:
    verify_html = verify_file.read()
with open(f'{file_dir}/html/register.html', 'r', encoding='utf8') as register_file:
    register_html = register_file.read()





@app.route("/verify") #接口主页面。form提交apikey和pwd
def verify():
    return verify_html

@app.route("/verifyed", methods=['GET', 'POST'])
def verifyed():
    api_key = request.form.get('api_key', type=str)
    password = request.form.get('password', type=str)
    verify_code = api_key + ', ' + password
    csv_dir = f'{file_dir}/database.csv'
    with open(csv_dir, "r", encoding="utf-8") as csv_file:
        csv = csv_file.read()
    if csv.find(verify_code) != -1:
        return 'verifyed.'
    else:
        return 'password error.'

@app.route("/register", methods=['GET', 'POST'])
def register():
    return register_html

@app.route("/registered", methods=['GET', 'POST'])
def registered():
    api_key = request.form.get('api_key', type=str)
    password = request.form.get('password', type=str)
    register_info = api_key + ', ' + password

    csv_dir = f'{file_dir}/database.csv'
    with open(csv_dir, "r", encoding="utf-8") as csv_file:
        old = csv_file.read()
    new = old + '\n' + register_info
    with open(csv_dir, "w", encoding="utf-8") as csv_file:
        csv_file.write(new)
    return register_info + ': registered.' #


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8090, debug=True)